import 'package:app_info/app_info.dart';
import 'package:app_info/info/appsflyer.dart';
import 'package:flutter/cupertino.dart';
import 'package:httpx/http_base_config.dart';
import 'package:httpx/library.dart';
import 'package:smartloan_mdc/extension/extension.dart';
import 'package:smartloan_mdc/res/string.dart';

import '../utils/loading/loading.dart';
import '../utils/locator/app_config.dart';
import '../utils/locator/locator.dart';

class AppHttpBaseConfig extends HttpxBaseConfig {

  @override
  BaseOptions getBaseOptions() {
    return BaseOptions(
      connectTimeout: 30000,
      receiveTimeout: 30000,
      baseUrl: '${locator<AppConfig>().getAppConfig().baseUrl}/api/',
      contentType: 'application/json;charset=UTF-8',
      headers: getBaseHeaders()
    );
  }

  @override
  void beforeRequest(bool isShowLoading) {
    // logW('beforeRequest showLoading value: $isShowLoading');
    if (isShowLoading) {
      showLoading();
    }
  }

  @override
  void afterRequest(bool isShowLoading) {
    if (isShowLoading) {
      hideLoading();
    }
  }

  // 处理业务码
  @override
  Future onResponse(data, Map extra) async {
    // 后端返回逻辑错误，统一100
    if (data is Map) {
      if (data['code'].toString() != "0") {

        if (extra['showError']) {
          if (data.containsKey('msg')) {
            data['msg'].toString().toast();
          }
        }

        throw HttpxException(100, data['msg'] ?? '');
      }

      if (data.containsKey('data')) {
        return data['data'];
      } else {
        return {};
      }

    } else {
      return data;
    }
  }

  // 处理http状态码而非业务码
  @override
  void onError(DioError error, Map? extra) {
    int UNKNOW = 400;
    int NETWORK = 500;
    String networkHint = AppStr.networkError;
    bool showError = true;

    // debugPrint('showError111: ${options.headers}');
    // debugPrint('showError111: ${options.extra}');

    if (extra != null) {
      if (extra.containsKey('showError')) {
        debugPrint('showError: ${extra}');
        showError = extra['showError'];
      }
    }

    // 暂时不区分具体错误，提示网络错误
    if (showError) AppStr.networkError.toast();

    switch(error.type) {
      case DioErrorType.sendTimeout:
      case DioErrorType.receiveTimeout:
      case DioErrorType.connectTimeout:
        throw HttpxException(NETWORK, networkHint);

      case DioErrorType.response:
        Response response = error.response!;
        int sCode = response.statusCode!;
        // logE('Dio Error Response > code: $sCode, data: ${response.data.toString()}');
        throw HttpxException(NETWORK, networkHint);

      case DioErrorType.other:
        if (error.message.contains("Network is unreachable")) {
          throw HttpxException(NETWORK, networkHint);
        }
        // logE('DioErrorType.other: ${error.toString()}');
        // networkHint.toast();
        throw HttpxException(NETWORK, error.toString());

      default:
        throw HttpxException(NETWORK, error.toString());
    }

  }

  Map<String, dynamic> getBaseHeaders() {
    // logW('getBaseHeaders 中 afId: ${Af().afId}');
    return {
      'lang': 'es',
      'packageName': AppInfo().packageName,
      'appName': AppInfo().appName,
      'afId': AppsFlyer().afId,
      // 'aFId': Af().afId, 移至interceptor
      // 'pkName': AppInfo().packageName,
      // 'nameOfApp': AppInfo().appName,
      // 'sourceOfLoan': CountryConfig().sourceNo,
      // 'eqInfo': AppInfo().androidId,
      // 'noOfCty': CountryConfig().countryCode,
      // 'verOfApp': AppInfo().version
    };
  }

  void exceptionHandle(Exception e, String pageName, BuildContext context) {
    // if (e is HttpxException) {
    //   if(e.code == 100) {
    //     if (e.message == 'token is expire' || e.message == 'Token Expirar') {
    //       AppRoute.pushAndRemoveUntil(context, const LoginPage());
    //       return;
    //     }
    //     e.message.toast(pageName);
    //   } else {
    //     CommonText.networkError.toast(pageName);
    //   }
    // } else {
    //   logE(e.toString());
    // }
  }

}